template <typename T>
class UnionFindSet
{
public:
    UnionFindSet()
    {
    }

    template <typename TContainer>
    UnionFindSet(const TContainer &container)
    {
        auto begin = container.begin();
        auto end = container.end();
        while (begin != end)
        {
            m[*begin] = *begin;
            ++begin;
        }
    }

    void insert(const T &value)
    {
        if (!m.count(value))
        {
            m[value] = value;
        }
    }

    bool exist(const T &value)
    {
        return m.count(value);
    }

    T find(const T &value)
    {
        if (m[value] == value)
        {
            return value;
        }
        return m[value] = find(m[value]);
    }

    void join(const T &value1, const T &value2)
    {
        if (find(value1) != find(value2))
        {
            m[find(value1)] = find(value2);
        }
    }

private:
    std::unordered_map<T, T> m;
};

class Solution
{
public:
    vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>> &edgeList, vector<vector<int>> &queries)
    {
        vector<int> queryIndex(queries.size());
        iota(queryIndex.begin(), queryIndex.end(), 0);
        sort(queryIndex.begin(), queryIndex.end(), [&](int i1, int i2)
             { return queries[i1][2] < queries[i2][2]; });
        sort(edgeList.begin(), edgeList.end(), [](auto &v1, auto &v2)
             { return v1[2] < v2[2]; });

        UnionFindSet<int> ufs;
        for (int i = 0; i < n; ++i)
        {
            ufs.insert(i);
        }

        vector<bool> result(queries.size());
        auto edgeIt = edgeList.begin();
        auto queryIndexIt = queryIndex.begin();
        while (queryIndexIt != queryIndex.end())
        {
            auto &query = queries[*queryIndexIt];
            while (edgeIt != edgeList.end())
            {
                auto &edge = *edgeIt;
                if (edge[2] < query[2])
                {
                    ufs.join(edge[0], edge[1]);
                    ++edgeIt;
                }
                else
                {
                    break;
                }
            }
            result[*queryIndexIt] = (ufs.find(query[0]) == ufs.find(query[1]));
            ++queryIndexIt;
        }

        return result;
    }
};